/*
 * @Author: 半生瓜 1515706227@qq.com
 * @Date: 2024-04-21 17:20:21
 * @LastEditors: 半生瓜 1515706227@qq.com
 * @LastEditTime: 2024-05-28 10:02:25
 * @FilePath: \vue-element-plus-admin-mini\src\hooks\web\useValidator.ts
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import { useI18n } from '@/hooks/web/useI18n'

const { t } = useI18n()

type Callback = (error?: string | Error | undefined) => void

interface LengthRange {
  min: number
  max: number
  message: string
}

export const useValidator = () => {
  const required = (message?: string) => {
    return {
      required: true,
      message: message || t('common.required')
    }
  }

  const lengthRange = (val: any, callback: Callback, options: LengthRange) => {
    const { min, max, message } = options
    if (val.length < min || val.length > max) {
      callback(new Error(message))
    } else {
      callback()
    }
  }

  const notSpace = (val: any, callback: Callback, message: string) => {
    // 用户名不能有空格
    if (val.indexOf(' ') !== -1) {
      callback(new Error(message))
    } else {
      callback()
    }
  }

  const notSpecialCharacters = (val: any, callback: Callback, message: string) => {
    // 密码不能是特殊字符
    if (/[`~!@#$%^&*()_+<>?:"{},.\/;'[\]]/gi.test(val)) {
      callback(new Error(message))
    } else {
      callback()
    }
  }

  // 两个字符串是否想等
  const isEqual = (val1: string, val2: string, callback: Callback, message: string) => {
    if (val1 === val2) {
      callback()
    } else {
      callback(new Error(message))
    }
  }

  // 只能输入英文
  const onlyEnglish = (val: string, callback: Callback, message: string) => {
    if (/^[a-zA-Z]+$/.test(val)) {
      callback()
    } else {
      callback(new Error(message))
    }
  }

  const noSpaceOrSpecialChars = (val: string, callback: Callback, message: string) => {
    // 使用正则表达式来检查输入中是否包含空格、特殊字符或中文字符
    if (/[\s`~!@#$%^&*()_+<>?:"{},.\/;'[\]\u4e00-\u9fa5]/.test(val)) {
      callback(new Error(message))
    } else {
      callback()
    }
  }

  return {
    required,
    lengthRange,
    notSpace,
    notSpecialCharacters,
    onlyEnglish,
    noSpaceOrSpecialChars
  }
}
